#!/usr/bin/env node
const commander = require('commander');
const ora = require('ora');
const fs = require('fs');
const inquirer = require('inquirer');
const shell = require('shelljs');
const child_process = require('child_process');
const handlebars = require('handlebars');
const path = require('path');

const questions = [
    {
        type: 'input',
        name: 'description',
        message: '请输入项目描述'
    },
    {
        type: 'input',
        name: 'version',
        message: '请输入项目项目版本号',
        default: '1.0.0'
    },
    {
        type: 'input',
        name: 'author',
        message: '请输入作者名称'
    }
  ];

const confirmQus =[
    {
      type: 'confirm',
      name: 'buildInCurrent',
      message: '当前目录已有同名项目，是否覆盖？',
      default: true
    }
  ]

commander.version('1.0.0', '-v, --version') //查询版本命令参数
.command('init [<name>]') //初始化子命令
.description('创建项目') // 命令描述说明
.action(name => { //命令执行操作
    if (!name) {
        commander.help()  //如果没有输入项目名称，显示help信息
        return
      }
    if (!fs.existsSync(name)) {//如果没有同名项目，就进行项目初始化
        init(name);
    } else {//有同名项目，询问是否覆盖
        inquirer.prompt(confirmQus).then(answers => {
            const buildInCurrent = answers.buildInCurrent;
            console.log(buildInCurrent);
            if(buildInCurrent){
                //删除同名项目
                init(name);//初始化新项目
            }else{
                return;
            }
        })
    }
})


function init (name){
    console.log('正在创建项目...');
    inquirer.prompt(questions).then(answers => {
        const spinner = ora('正在下载模板...\n');
        spinner.start();
        child_process.exec('git clone https://gitee.com/li-xia-han/lagou-task.git', function(err, stdout, stderr) {
            if (err) {
            spinner.fail();
            console.log('模板下载失败')
            } else {
                spinner.succeed();
                shell.mv(process.cwd() + '/lagou-task', process.cwd() + '/' + name)
                const fileName = `${name}/package.json`;
                const meta = {
                    name,
                    description: answers.description,
                    version: answers.version,
                    author: answers.author
                }
                if(fs.existsSync(fileName)){
                    const content = fs.readFileSync(fileName).toString();
                    let dt = JSON.parse(content);
                        dt.name = '{{name}}';
                        dt.description = '{{description}}';
                        dt.version = '{{version}}';
                        dt.author = '{{author}}';
                        const result = handlebars.compile(JSON.stringify(dt, null, 4))(meta);
                        fs.writeFileSync(fileName, result);
                        console.log('项目初始化完成');
                }else {
                        console.log('package不存在')
                }
            }
        })
        })
}


commander.parse(process.argv);